package com.vfa.vocaburay;

import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.preference.PreferenceManager.OnActivityResultListener;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.vfa.data.ExportData;
import com.vfa.data.Word;
import com.vfa.data.WordData;
import com.vfa.data.toastMaking;
import com.vfa.speech.SpeechText;
import com.vfa.test.QuestionAdapter;

public class WordList extends ListActivity implements OnInitListener{
	private static final int DIALOG_WORD_DETAIL = 1;
	private ArrayList<Word> wordList = null;
	private ArrayList<Word> miniwordList = null;
	private WordAdapter m_adapter;
	private Button addNewWordButton;
	private Button nextPageButton;
	private Button prePageButton;
	private Button searchButon;
	private Button btImport;
	private Button btExport;

	private String searchCategory;
	private String dateOne;
	private String dateTwo;
	private String keyWord;
	
	private TextToSpeech mTts;
    private int MY_DATA_CHECK_CODE = 0;
    private int requestNewWordCode= 1;
    private WordData wordData;
	private int startpoint=0;
	private int numofstep = 7;
	private int endpoint = startpoint+numofstep;
	Typeface font;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.wordlist);
		font = Typeface.createFromAsset(getAssets(), "ariali.ttf");  
		wordData = new WordData(this);
		addNewWordButton = (Button) findViewById(R.id.addNewWordButton);
		nextPageButton = (Button) findViewById(R.id.NextPage);
		prePageButton = (Button) findViewById(R.id.prePage);
		searchButon = (Button) findViewById(R.id.searchButton);
		btImport =(Button) findViewById(R.id.btImportFromFile);
		btExport = (Button) findViewById(R.id.btExportWords);
		wordList = new ArrayList<Word>();
		miniwordList = new ArrayList<Word>();
		Bundle bundle = getIntent().getExtras();
		//registerForContextMenu(getListView());
		this.m_adapter = new WordAdapter(getApplicationContext(),
				R.layout.oneword, wordList);
		setListAdapter(this.m_adapter);

		if (bundle != null) {
			//addNewWordButton.setText("Word List");

			searchCategory = bundle.getString("searchCategory");
			if (searchCategory.equals("byDate")) {
				dateOne = bundle.getString("dateOne");
				dateTwo = bundle.getString("dateTwo");
	/*			 toastMaking.infoToast(getApplicationContext(),
				 dateOne+" "+dateTwo).show();*/
				loadWordByDate(dateOne, dateTwo);
			} else if (searchCategory.equals("byKeyWord")) {
				keyWord = bundle.getString("keyWord");
				/*toastMaking.infoToast(getApplicationContext(), keyWord).show();*/
				loadWordByKeyWord(keyWord);
			}
			else if (searchCategory.equals("combo")) {
				dateOne = bundle.getString("dateOneCB");
				dateTwo = bundle.getString("dateTwoCB");
				keyWord = bundle.getString("keyWordCB");
				/*toastMaking.infoToast(getApplicationContext(), keyWord).show();*/
				loadWordByCombo(dateOne,dateTwo,keyWord);
			}
		} else {
			//addNewWordButton.setText("New Word");
			ShowAllData();
		}
		// set up pages
		
		addNewWordButton.setOnClickListener(addNewWord_listener);
		nextPageButton.setOnClickListener(nextPage_listener);
		prePageButton.setOnClickListener(prePage_listener);
		searchButon.setOnClickListener(search_listener);
		btImport.setOnClickListener(importListener);
		btExport.setOnClickListener(exportListener);
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		
	}
	
//	@Override
//	protected void onStart() {
//		// TODO Auto-generated method stub
//		super.onStart();
//		loadWordByDefault();
//		
//		StartSTT();
//	}
//	

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		// TODO Auto-generated method stub
		
		Word temp = (Word) l.getItemAtPosition(position);
		detailDialog( temp).show();
		//Toast.makeText(getBaseContext(), temp.getwordName() + " is choose!", Toast.LENGTH_SHORT).show();
	}


	private class WordAdapter extends ArrayAdapter<Word> {

		private ArrayList<Word> items;

		public WordAdapter(Context context, int textViewResourceId,
				ArrayList<Word> items) {
			super(context, textViewResourceId, items);
			this.items = items;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View v = convertView;
			if (v == null) {
				LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				v = vi.inflate(R.layout.oneword, null);
			}
			Word w = items.get(position);
			if (w != null) {
				TextView tt = (TextView) v.findViewById(R.id.WordName);
				TextView bt = (TextView) v.findViewById(R.id.WordSpeech);
				TextView mt = (TextView) v.findViewById(R.id.tvWordMean);
				TextView rt = (TextView) v.findViewById(R.id.tvRead);
				rt.setTypeface(font);
				if (tt != null) {
					tt.setText(w.getwordName());
				}
				if (bt != null) {
					bt.setText(w.getwordCategory());
				}
				if(mt!=null)
					mt.setText(w.getwordMeaning());
				if(rt!=null)
					rt.setText(w.getWordRead());
			}
			return v;
		}
	}

	private OnClickListener addNewWord_listener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			//if (addNewWordButton.getText().equals("New Word")) {
				Intent intent = new Intent(WordList.this, InputWord.class);
				startActivityForResult(intent,requestNewWordCode);
				//WordList.this.finish();
//			} else if (addNewWordButton.getText().equals("Word List")) {
//				Intent intent = new Intent(WordList.this, WordList.class);
//				startActivity(intent);
//				WordList.this.finish();
//			}
		}
	};
	private void doPrev()
	{
		if(startpoint!=0){
			if(startpoint>numofstep){
			startpoint =  startpoint - numofstep;
			endpoint = endpoint - numofstep;
			}
			else {
				startpoint =  0;
				endpoint = numofstep;
			}
			
			System.out.println("startpoint " + startpoint);
			System.out.println("endpoint " + endpoint);
			ShowAllData();
		
		}
		else{
			ShowAllData();
		}
	}

	private OnClickListener nextPage_listener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			if (wordList.size() == numofstep) {
				startpoint = startpoint + numofstep;
				endpoint = startpoint+numofstep;
				
				System.out.println("startpoint " + startpoint);
				System.out.println("endpoint " + endpoint);
				ShowAllData();
				
			}
		}
	};
	private OnClickListener prePage_listener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			doPrev();

		}
	};
	private OnClickListener search_listener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			Intent intent = new Intent(WordList.this, SearchOption.class);
			startActivity(intent);
			//WordList.this.finish();
		}
	};
	private OnClickListener importListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			Intent intent = new Intent(WordList.this, ImportFileCSV.class);
			startActivityForResult(intent,requestNewWordCode);
			//WordList.this.finish();
		}
	};
	private OnClickListener exportListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			Intent intent = new Intent(WordList.this, ExportData.class);
			startActivity(intent);
			//WordList.this.finish();
		}
	};
/*	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		menu.add(0, R.string.viewword, 0, "View Word");
		menu.add(0, R.string.updateword, 1, "Update Word");
		menu.add(0, R.string.deleteword, 2, "Delete Word");
		menu.add(0, R.string.readword, 3, "Read Word");
		super.onCreateContextMenu(menu, v, menuInfo);
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		int itemId = (int) ((AdapterView.AdapterContextMenuInfo) item
				.getMenuInfo()).id;
		Word word = miniwordList.get(itemId);
		switch (item.getItemId()) {

		case R.string.deleteword:
			for (int i = 0; i < miniwordList.size(); i++) {
				if (word.getwordName()
						.equals(miniwordList.get(i).getwordName())) {
					vfaMain.wordData.delete(word.getwordName());
					wordList.remove(word);	
					m_adapter.notifyDataSetChanged();
					break;
				}			
			}
			m_adapter.clear();
			getWords();
			setButton();
			break;
		case R.string.updateword:
			Intent intent = new Intent(WordList.this, updateWord.class);
			intent.putExtra("wordName", word.getwordName()).putExtra(
					"wordMeaning", word.getwordMeaning()).putExtra(
					"wordExample", word.getwordExample()).putExtra(
					"wordCategory", word.getwordCategory()).putExtra(
					"wordLanguage", word.getwordLanguage());
			startActivity(intent);
			WordList.this.finish();
			break;
		case R.string.viewword:
			String name = "word's details";
			String detail = word.getDetails();
			//detailDialog(name, detail);
			break;
			
		case R.string.readword:
			String text = word.getwordName().toString();
		
			System.out.println("Doc text nay:    "+text);
			if (text!=null && text.length()>0) {
				try {
					mTts.speak(text, TextToSpeech.QUEUE_ADD, null);
				} catch (Exception e) {
					System.out.println("doc  bi loi!!!    ");
				}
				
		    }
			
			
			
			break;
		}
		return super.onContextItemSelected(item);
	}
*/
	private AlertDialog detailDialog(final Word word) {
		return new AlertDialog.Builder(this).setTitle(word.getwordName()).setMessage(word.getDetails())
				.setPositiveButton("Update", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {

                    	Intent intent = new Intent(WordList.this, updateWord.class);
            			intent.putExtra("wordName", word.getwordName()).putExtra(
            					"wordMeaning", word.getwordMeaning()).putExtra(
            					"wordRead", word.getWordRead()).putExtra(
            					"wordExample", word.getwordExample()).putExtra(
            					"wordCategory", word.getwordCategory()).putExtra(
            					"wordLanguage", word.getwordLanguage()).putExtra(
                    					"wordID", word.getWordID());
            			startActivity(intent);
            			WordList.this.finish();
                    }
                })
                .setNeutralButton("Delete", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {

            			
            					int result = wordData.delete(word.getWordID());
            					if(result > 0)
            					{
            						wordList.remove(word);
            						if(wordList.size() ==0){
            							doPrev();
            						}
            						else
            							ShowAllData();
            							
            						Toast.makeText(getBaseContext(), "Delete "+ word.getwordName() +"  successful!", Toast.LENGTH_SHORT).show();
									Log.d("kitvs", "Delete word '"+word.getwordName()  +"'sucessful");
            					}
            					else
            					{
            						Toast.makeText(getBaseContext(), "Delete "+ word.getwordName() +"  failed!", Toast.LENGTH_SHORT).show();
            						Log.d("kitvs", "Delete word '"+word.getwordName()  +"'failed!");
            					}
            			
                    }
                })
                .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {

                        /* User clicked Cancel so do some stuff */
                    }
                })

				.create();
				

	}

	@Override
	public void onBackPressed() {
		//Intent intent = new Intent(WordList.this, vfaMain.class);
		//startActivity(intent);
		WordList.this.finish();
	}


	private void loadWordByDate(String param1, String param2) {
		try {
			wordList = wordData.getDatabaseByDate(param1, param2);
			this.m_adapter = new WordAdapter(getApplicationContext(),
					R.layout.oneword, wordList);
			setListAdapter(m_adapter);
			/*wordList = vfaMain.wordData.getDatabaseByDate("2010-01-01",
			 "2011-12-12");*/
		} catch (Exception e) {
		}
	}

	private void loadWordByKeyWord(String param3) {
		try {
			wordList = wordData.searchWord(param3);
			this.m_adapter = new WordAdapter(getApplicationContext(),
					R.layout.oneword, wordList);
			setListAdapter(m_adapter);
			/*wordList = vfaMain.wordData.searchWord("f");*/
		} catch (Exception e) {
		}
	}
	private void loadWordByCombo(String param1, String param2 , String param3) {
		try {
			wordList = wordData.getDataBaseByDateAndKey(param1, param2, param3);
			this.m_adapter = new WordAdapter(getApplicationContext(),
					R.layout.oneword, wordList);
			setListAdapter(m_adapter);
			/*wordList = vfaMain.wordData.searchWord("f");*/
		} catch (Exception e) {
		}
	}


	@Override
	public void onInit(int status) {
		if (status == TextToSpeech.SUCCESS) {
            //Toast.makeText(getApplicationContext(), "Text-To-Speech engine is initialized", Toast.LENGTH_LONG).show();
		}
		else if (status == TextToSpeech.ERROR) {
			Toast.makeText(getApplicationContext(),"Error occurred while initializing Text-To-Speech engine", Toast.LENGTH_LONG).show();
		}
		
	}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == MY_DATA_CHECK_CODE) {
            if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
                // success, create the TTS instance
            	mTts = new TextToSpeech(this, this);
            } 
            else {
                // missing data, install it
                Intent installIntent = new Intent();
                installIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
                startActivity(installIntent);
            }
        }
        else if(requestCode == requestNewWordCode)
        {
        	if(resultCode == RESULT_OK)
        	{
        		ShowAllData();
        	}
        }
        	

    }
	public void StartSTT(){
		Intent checkIntent = new Intent();
		checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
		startActivityForResult(checkIntent, MY_DATA_CHECK_CODE);
	}
	private void ShowAllData(){
		//arrlistquestion = data.getQuestion(4);
		wordList = wordData.getWordsLimit(startpoint, numofstep);
		//if(wordList.size()!=0)
		{
		this.m_adapter = new WordAdapter(getApplicationContext(),
				R.layout.oneword, wordList);
		setListAdapter(m_adapter);
		}
	}
}
